/*
 * BAM.c
 *
 * Created: 11/10/2013 3:20:55 PM
 *  Author: Daniel Keith
 */ 

#include <avr/io.h>
#include "util.h"
#include <string.h>

/** Initializes the serial commutation
*	It sets the baud in order commutate over a BAM device.
*	It sets the frame format and enables the receiver and transmitter.
*/

 void serial_init(void){
	 unsigned int baud =34;
	 
	 /* Set baud rate */
	 UBRR0H = (unsigned char) (baud >> 8);
	 UBRR0L = (unsigned char) baud;
	 
	 /* Enable double speed mode */
	 UCSR0A = 0b00000010;
	 
	 /*set frame format: 8 data bits, 1 stop bits */
	 UCSR0C = 0b00000110;
	 
	 /* enable receiver and transmitter */
	 UCSR0B = 0b00011000;
	 
 }
 
 /** transmits desired characters to terminal
 *	 receives a character through the variable data to have transmitted to terminal.
 *	 @param data is a char 
 */
 
 void serial_putc(char data){
	 /*Wait for empty transmit buffer by checking the UDRE bit */
	 while((UCSR0A & 0b00100000)==0);
	 
	 /*Put data into transmit buffer; sends the data */
	 UDR0 = data;
 }
 
 /** receives characters trough the terminal 
 *	 receives a character from the terminal that is returned as char
 *	 @param data is the information that need to be transmitted to terminal
 */
 
 char serial_getc(){
	 /*wait for the receieve complete flag (RXC) */
	 while ((UCSR0A & 0b10000000)==0);
	 
	 /*reads data from the receive buffer; clears the receive buffer */
	 return UDR0;
 }
 
 /** transmits arrays to the terminal
*	 use a pointer to navigate arrays and transmits them to the terminal use serial_putc
*	 @param *str is a pointer thats pointing into an array
*/
 void serial_puts(char *str) {
	 while(*str != 0) {
		 serial_putc(*str);
		 str++;
	 }		 
 }